//
//  SQLiteClient+Account.swift
//  LiteAccount
//
//  Created by 刘伟 on 2017/5/18.
//  Copyright © 2017年 刘伟. All rights reserved.
//



extension SQLiteClient {
    
    func initAccount() {
        _ = db.execute(sql: "create table if not exists tb_account(id int primary key, amount decimal(20,2), note varchar(255), date varchar(255))")
        let data = db.query(sql: "select * from tb_account")
        if data.count == 0 {
            let sql = "insert into tb_account (id, amount, note, date) values (1, 0.00, '心情不错', '')"
            _ = db.execute(sql: sql)
        }
    }
    
    func initAccountDetail() {
        _ = db.execute(sql: "create table if not exists tb_account_detail(account_id int default 1, category_id int default 0, name varchar(255), amount decimal(20,2) default 0.00, date varchar(255))")
    }
    
    func fetchAccount() -> AccountModel {
        let data = db.query(sql: "select * from tb_account")
        var account = AccountModel(dic: data[0])
        account.detail = fetchAccountDetail()
        return account
    }
    
    func fetchAccountDetail() -> [AccountDetailModel] {
        let data = db.query(sql: "select * from tb_account_detail where account_id=1")
        var detailList = [AccountDetailModel]()
        for i in 0 ..< data.count {
            let detail = AccountDetailModel(dic: data[i])
            detailList.append(detail)
        }
        return detailList
    }
    
    func updateAccountMoney() {
        let sql = "select * from tb_account_detail where account_id = 1"
        let rowsDetail = db.query(sql: sql)
        var accountAmount = 0.00
        for i in 0 ..< rowsDetail.count {
            accountAmount += rowsDetail[i]["amount"] as! Double
        }
        _ = db.execute(sql: "update tb_account set amount = \(accountAmount) where id = 1")
    }
    
    func updateAccountDetailBy(name: String, amount: String, getResponse:@escaping (_ response: ClientResponseType) -> Void) {
        var response: ClientResponseType
        let sql = "UPDATE tb_account_detail SET amount = \(amount) WHERE name = '\(name)'"
        let rs = db.execute(sql: sql)
        if rs == 0 {
            // 失败
            response = .failure("编辑资产失败")
        } else {
            response = .success(rs as AnyObject, "编辑资产成功")
        }
        updateAccountMoney()
        getResponse(response)
    }
    
    func addAccountDetailBy(name: String, amount: String, getResponse:@escaping (_ response: ClientResponseType) -> Void) {
        var response: ClientResponseType
        let data = db.query(sql: "select * from tb_account_detail where name = '\(name)'")
        if data.count > 0 {
            response = .failure("亲，此资产名已存在")
            getResponse(response)
            return
        }
        let sql = "insert into tb_account_detail (name, amount) values ('\(name)', \(amount))"
        let rs = db.execute(sql: sql)
        if rs == 0 {
            // 失败
            response = .failure("添加资产失败")
        } else {
            response = .success(rs as AnyObject, "添加资产成功")
        }
        updateAccountMoney()
        getResponse(response)
    }
    
    // MARK: 删除资产记录通过 名称
    func deleteAccountDetailBy(name: String, getResponse:@escaping (_ response: ClientResponseType) -> Void) {
        var response: ClientResponseType
        let sql = "delete from tb_account_detail where name = '\(name)'"
        let rs = db.execute(sql: sql)
        if rs == 0 {
            // 失败
            response = .failure("删除资产失败")
        } else {
            response = .success(rs as AnyObject, "删除资产成功")
        }
        updateAccountMoney()
        getResponse(response)
    }
    
    func getAccountDataForSave(getResponse:@escaping (_ response: ClientResponseType) -> Void) {
        var response: ClientResponseType
        let accountData = db.query(sql: "select * from tb_account")
        let detailData = db.query(sql: "select * from tb_account_detail where account_id=1")
        if detailData.count == 0 || accountData.count == 0 {
            response = .failure("账本信息不能喂空")
            getResponse(response)
            return
        }
        guard let accountJson = objToJSON(obj: accountData[0] as AnyObject), let detailJson = objToJSON(obj: detailData as AnyObject) else {
            response = .failure("获取账户数据失败")
            getResponse(response)
            return
        }
        let data = (accountJson,detailJson)
        response = .success(data as AnyObject, "获取数据成功")
        getResponse(response)
    }
    
    func rewriteCurrentAccount(account: AccountModel, getResponse:@escaping (_ response: ClientResponseType) -> Void) {
        var response: ClientResponseType
        // 更新账本
        let rs = db.execute(sql: "update tb_account set amount = \(account.amount), note = '\(account.note)' where id = 1")
        if rs == 0 {
            // 失败
            response = .failure("账本更新失败")
            getResponse(response)
            return
        }
        
        // 删除所有资产
        var sql = "delete from tb_account_detail where account_id = 1"
        _ = db.execute(sql: sql)
        for detail in account.detail {
            sql = "insert into tb_account_detail (name, amount) values ('\(detail.name)', \(detail.amount))"
            _ = db.execute(sql: sql)
        }
        response = .success(rs as AnyObject, "更新成功")
        getResponse(response)
    }
    
}
